const mysqlClient = require('../libs/mysqlClient');
const redisClient = require('../libs/redisClient');
const encryptUitl = require('../utils/encryptUtils');

function Service() {
    this.list = function (params, callback) {
        var sql = mysqlClient.buildQuerySql('t_organization', params, true);
        mysqlClient.queryPage(sql, null, params.pageNumber, params.pageSize, callback);
    };
    // 根据id获取组织
    this.retrieve = function (id, params, callback) {
        mysqlClient.getObject('t_organization', {id: id}, callback);
    };
    // 新增
    this.create = function (params, callback) {
        mysqlClient.addObject('t_organization', params, callback);
    };
    // 更新
    this.update = function (id, params, callback) {
        mysqlClient.getObject('t_organization', {id}, function (data) {
            if (data) {
                const {sid} = params;
                delete params.sid;
                if (params.password&&params.password!=='') {
                    params.password = encryptUitl.encrypt(params.password, data.salt);
                }else {
                    delete params.password;
                }
                mysqlClient.updateObject('t_organization', params, {id}, ()=>{
                    callback();
                    mysqlClient.getObject('t_organization', {id}, function (data) {
                        redisClient.set(sid, data)
                    });
                });

            } else {
                callback({error: '没有数据'});
            }
        });
    };
    // 删除
    this.delete = function (id, params, callback) {
        mysqlClient.deleteObject('t_user', {id: id}, callback);
    }
}

exports.service = Service;
